package com.example.threadlocaldemo0.dao;

import com.example.threadlocaldemo0.utils.ConnectionContainer;
import com.example.threadlocaldemo0.utils.JdbcUtils;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@Repository
public class AllDao {

    public int insertOrder(String userId, String commodityCode, Integer count, Integer money) throws SQLException {
        Connection conn = ConnectionContainer.getConnection();
        String sql = "INSERT INTO `order` ( user_id, commodity_code, count, money ) VALUES ( ?, ?, ?, ? )";
        PreparedStatement pst = conn.prepareStatement(sql);
        pst.setString(1, userId);
        pst.setString(2, commodityCode);
        pst.setInt(3, count);
        pst.setInt(4, money);

        int i = pst.executeUpdate();

        JdbcUtils.quietlyClose(pst);

        return i;
    }

    public int updateAccount(String userId, Integer money) throws SQLException {
        Connection conn = ConnectionContainer.getConnection();
        String sql = "update `account` set `money` = `money` - ? where `user_id` = ?";
        PreparedStatement pst = conn.prepareStatement(sql);
        pst.setInt(1, money);
        pst.setString(2, userId);

        int i = pst.executeUpdate();
        JdbcUtils.quietlyClose(pst);
        return i;
    }

    public int updateStorage(String commodityCode, Integer count) throws SQLException {
        Connection conn = ConnectionContainer.getConnection();
        String sql = "update `storage` set `count` = `count` - ? where `commodity_code` = ?";
        PreparedStatement pst = conn.prepareStatement(sql);
        pst.setInt(1, count);
        pst.setString(2, commodityCode);

        int i = pst.executeUpdate();
        JdbcUtils.quietlyClose(pst);

        throw new RuntimeException("故意抛出异常");
//        return i;
    }

}